package io.renren.controller;

import com.lly835.bestpay.model.PayResponse;
import io.renren.entity.OrderDTO;
import io.renren.service.PayService;
import io.renren.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.UUID;

/**
 * 支付
 * Created by 廖师兄
 * 2017-07-04 00:49
 */
@Controller
@RequestMapping("/pay")
public class PayController {


    @Autowired
    private PayService payService;
    @Autowired
    TokenService tokenService;

    @RequestMapping("/createVip")
    public String create(HttpServletRequest request, @RequestParam("token") String token,
                         @RequestParam("returnUrl") String returnUrl,
                         @RequestParam("level") String level,
                         Map<String, Object> map) {
        OrderDTO orderDTO = payService.getPayLevelVip(level);
        orderDTO.setOrderId(UUID.randomUUID().toString().substring(0,20));
        orderDTO.setBuyerOpenid(tokenService.getOpenIdByToken(token));
        //1. 查询订单
//        OrderDTO orderDTO = orderService.findOne(orderId);
//        if (orderDTO == null) {
//            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
//        }

        //2. 发起支付
        PayResponse payResponse = payService.create(orderDTO);

        map.put("payResponse", payResponse);
     //   map.put("returnUrl", returnUrl);
//        request.setAttribute("appId", payResponse.getAppId());
//        request.setAttribute("timeStamp", payResponse.getTimeStamp());
//        request.setAttribute("package", payResponse.getPackAge());
//        request.setAttribute("paySign", payResponse.getPaySign());
        return"redirect:"+returnUrl+"?appId="+payResponse.getAppId()+"&timeStamp="+payResponse.getTimeStamp()+"&package="+payResponse.getPackAge()+"&paySign="+payResponse.getPaySign()+"&nonceStr="+payResponse.getNonceStr();
    }

    /**
     * 微信异步通知
     * @param notifyData
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) throws Exception {
        payService.notify(notifyData);

        //返回给微信处理结果
        return new ModelAndView("pay/success");
    }


}
